package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/customer/internal/svc"
	"insighttracking/apps/customer/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type RefundSpuByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewRefundSpuByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *RefundSpuByIdApiLogic {
	hostname, _ := os.Hostname()
	return &RefundSpuByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *RefundSpuByIdApiLogic) RefundSpuByIdApi(req *types.RefundReq) (resp string, err error) {
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	customerId := cast.ToInt64(l.ctx.Value("customerId"))
	ordersEntity, err := dao.OrdersEntity.WithContext(l.ctx).Where(
		dao.OrdersEntity.ID.Eq(req.ID),
		dao.OrdersEntity.CustomerID.Eq(customerId),
		dao.OrdersEntity.EnterpriseID.Eq(enterpriseId),
	).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的主键错误")
	}
	if ordersEntity.Status != enum.OrdersCreateEnum {
		return "", errors.New("当前订单状态不支持退货")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	if _, err = tx.OrdersEntity.WithContext(l.ctx).Where(dao.OrdersEntity.ID.Eq(req.ID)).UpdateSimple(
		dao.OrdersEntity.Status.Value(enum.OrdersCancelEnum),
	); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("退货失败")
	}

	// 取消采购计划
	ordersDetailEntity, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{req.ID})
	if err == nil && len(ordersDetailEntity) > 0 {
		for _, item := range ordersDetailEntity {
			if item.Status != enum.OrdersCreateEnum {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("退货失败")
			}
			if err = service.OrdersDetailService.ModifyStatusByIdListApi(l.ctx, tx, []int64{item.ID}, enum.OrdersCancelEnum); err != nil {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("退货失败")
			}
			planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailIdApi(l.ctx, item.ID)
			if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
			}
			if planOrdersEntities.ID > 0 {
				if err = tx.Rollback(); err != nil {
					return "", err
				}
				return "", errors.New("订单已进入生产阶段，请联系工作人员处理")
			}

			// 采购计划和订单的关系
			//planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailIdApi(l.ctx, item.ID)
			//if !errors.Is(err, gorm.ErrRecordNotFound) {
			//	purchasePlanEntity, err := service.PurchasePlanService.GetByIdApi(l.ctx, planOrdersEntities.PurchasePlanID)
			//	if !errors.Is(err, gorm.ErrRecordNotFound) {
			//		if item.SpuCount.Equal(purchasePlanEntity.RequirementsCount) {
			//			if err = service.PurchasePlanService.ModifyStatusByIdListApi(l.ctx, tx, []int64{planOrdersEntities.PurchasePlanID}, 30); err != nil {
			//				if err = tx.Rollback(); err != nil {
			//					return "", err
			//				}
			//				return "", errors.New("退货失败")
			//			}
			//		} else {
			//			// 减少采购计划数量
			//			if err = service.PurchasePlanService.ModifyRequirementsCountByIdApi(l.ctx, tx, planOrdersEntities.PurchasePlanID, purchasePlanEntity.RequirementsCount.Sub(item.SpuCount)); err != nil {
			//				if err = tx.Rollback(); err != nil {
			//					return "", err
			//				}
			//				return "", errors.New("退货失败")
			//			}
			//		}
			//	}
			//}
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("退货失败")
	}
	return "操作成功", nil
}
